/**
 * Copyright (c) 2024,  科泰集团教研团队
 * 版权所有，请勿侵权
 */
package com.ktjiaoyu.news.servlet.api;

import com.alibaba.fastjson.JSON;
import com.ktjiaoyu.news.utils.R;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 可匿名上传文件的测试接口，正式环境需删除
 * @author 科泰集团教研团队
 * @createTime 2024-4-9 17:36:33
 * @lastModify 2024-4-9 17:36:33
 * @version 1.0.0
 */
@WebServlet(name = "AnonUploadServlet", urlPatterns = "/api/upload")
@MultipartConfig(maxFileSize = 1024 * 1024 * 50) // 最多传50M
public class AnonUploadServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        // 返回的json对象
        R result = null;
        try {
            // 获取文件Part
            Part file = request.getPart("file");
            // 获取提交的文件名
            String fileName = file.getSubmittedFileName();
            final String uploadPath = "/statics/upload/";
            // 获取项目运行的真实路径
            String realPath = request.getServletContext().getRealPath(uploadPath);
            // 如果路径不存在，则创建
            File root = new File(realPath);
            if(!root.exists()){
                root.mkdirs();
            }
            // 保存文件
            file.write(realPath + fileName);
            // 把文件请求路径作为返回结果
            result = R.ok(uploadPath + fileName);
        }catch (Exception e){
            e.printStackTrace();
            // 上传失败
            result = R.fail(e.getMessage());
        }
        PrintWriter out = response.getWriter();
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
